package com.neteast.androidclient.newscenter.activity;


import java.util.Random;

import com.neteast.androidclient.newscenter.R;
import com.tencent.weibo.beans.OAuth;
import com.tencent.weibo.utils.OAuthClient;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;

public class QQWebViewActivity extends Activity {
	
	private Activity context;
	public static final String CONSUMER_KEY = "801130933";
	public static final String CONSUMER_SECRET = "fb9dd467927353736b399c9928de054e";
	
	protected static final int REQUEST_TOKEN_ERROR = 0;
	protected static final int REQUEST_TOKEN_SUCCESS = 1;
	protected static final int OAUTH_IS_READY = 2;
	
	public static OAuth oAuth;
	public static OAuthClient auth;
	private AlertDialog connDialog;
	
	private Handler handler=new Handler(){
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case REQUEST_TOKEN_ERROR:
				if (connDialog.isShowing()) {
					connDialog.dismiss();
				}
				Toast.makeText(context, "绑定QQ失败", Toast.LENGTH_SHORT).show();
				setResult(RESULT_CANCELED);
				finish();
				break;
			case REQUEST_TOKEN_SUCCESS:
				if (connDialog.isShowing()) {
					connDialog.dismiss();
				}
				String url=(String) msg.obj;
				webView.loadUrl(url);
				break;
			case OAUTH_IS_READY:
				if (connDialog.isShowing()) {
					connDialog.dismiss();
				}
				setResult(OAUTH_IS_READY);
				finish();
				break;
			}
		}
	};
	private WebView webView;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		getWindow().requestFeature(Window.FEATURE_PROGRESS);
		setContentView(R.layout.layout_qq_oauth_request);
		getWindow().setGravity(Gravity.LEFT);
		getWindow().setLayout(350, ViewGroup.LayoutParams.MATCH_PARENT);
		init();
	}
	
	private void init() {
		createDialog();
		webView = (WebView) findViewById(R.id.qqweb);
		WebSettings settings = webView.getSettings();
		settings.setJavaScriptEnabled(true);
		settings.setAllowFileAccess(true);
		webView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				context.setProgress(newProgress * 1000);
			}
		});
		webView.setWebViewClient(new WebViewClient(){
			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				return true;
			}
			@Override
			public void onPageStarted(WebView view, String path, Bitmap favicon) {
				super.onPageStarted(view, path, favicon);
				Log.i("test", "path="+path);
				if (path.contains("qweibo4android://AuthUserCenter?")) {
						setResult(RESULT_OK, new Intent().setData(Uri.parse(path)));
						finish();
				}
			}
		});
		getRequestToken();
	}

	private void createDialog() {
		connDialog = new AlertDialog.Builder(context).create();
		connDialog.setTitle("提示");
		connDialog.setMessage("连接中...");
		connDialog.setIcon(getResources().getDrawable(R.drawable.ic_progress));
		connDialog.setCanceledOnTouchOutside(false);
		connDialog.setCancelable(false);
		connDialog.getWindow().setGravity(Gravity.LEFT);
		LayoutParams layoutParams = new LayoutParams();
		layoutParams.x=61;
		connDialog.getWindow().setAttributes(layoutParams);
	}

	private void getRequestToken() {
		connDialog.show();
		new Thread(new Runnable() {
			public void run() {
				oAuth = new OAuth("qWeibo4android://AuthUserCenter");
				oAuth.setOauth_consumer_key(CONSUMER_KEY);
				oAuth.setOauth_consumer_secret(CONSUMER_SECRET);
				//已经有access token
				if (isValidate(context)) {
					oAuth=getOAuth(context);
					handler.sendEmptyMessage(OAUTH_IS_READY);
					return;
				} else {
					auth = new OAuthClient();// OAuth 认证对象
					// 获取request token
					try {
						oAuth = auth.requestToken(oAuth);
					} catch (Exception e) {
						handler.sendEmptyMessage(REQUEST_TOKEN_ERROR);
						return;
					}
					if (oAuth.getStatus() == 1) {
						handler.sendEmptyMessage(REQUEST_TOKEN_ERROR);
						return;
					} else {
						String oauth_token = oAuth.getOauth_token();
						Log.i("test", "oauth_token="+oauth_token);
						if (TextUtils.isEmpty(oauth_token)) {
							handler.sendEmptyMessage(REQUEST_TOKEN_ERROR);
							return;
						}
						String url = "http://open.t.qq.com/cgi-bin/authorize?oauth_token="+ oauth_token;
						handler.sendMessage(handler.obtainMessage(REQUEST_TOKEN_SUCCESS, url));
					}
				}
			}
		}).start();
	}

	public void backToShareCenter(View view) {
		setResult(RESULT_CANCELED);
		finish();
	}
	
	public static class TokenStore {
		
		public static String fileName = "token_store";
		
		public static void store(Context context, OAuth oauth) {
			SharedPreferences settings = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
			
			SharedPreferences.Editor editor = settings.edit();
			
			editor.putString("oauth_token", oauth.getOauth_token());
			editor.putString("oauth_token_secret", oauth.getOauth_token_secret());	
			
			editor.commit();		
		}
		
		public static String[] fetch(Context context) {
			SharedPreferences settings = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
			
			String oauth_token = settings.getString("oauth_token", null);
			String oauth_token_secret = settings.getString("oauth_token_secret", null);
			
			return new String[] {oauth_token, oauth_token_secret};
		}
		
		public static void clear(Context context) {
			SharedPreferences settings = context.getSharedPreferences(fileName, Context.MODE_PRIVATE);
			SharedPreferences.Editor editor = settings.edit();
			editor.clear();  
	        editor.commit(); 
		}	
	}
	
	public static boolean isValidate(Context context) {
		String[] fetch = TokenStore.fetch(context);
		return fetch[0] != null && fetch[1] != null;
	}
	
	public static OAuth getOAuth(Context context) {
		Random random=new Random();
		OAuth oAuth=new OAuth();
		String[] fetch = QQWebViewActivity.TokenStore.fetch(context);
		String oauth_token=fetch[0];
		String oauth_token_secret=fetch[1];
		oAuth.setOauth_token(oauth_token);
		oAuth.setOauth_token_secret(oauth_token_secret);
		oAuth.setOauth_timestamp(String.valueOf(System.currentTimeMillis() / 1000));
		oAuth.setOauth_nonce(String.valueOf(random.nextInt(9876599) + 123400));
		oAuth.setOauth_consumer_key(CONSUMER_KEY);
		oAuth.setOauth_consumer_secret(CONSUMER_SECRET);
		return oAuth;
	}
}
